import { Component, PropTypes } from 'labrador-immutable';
import immutable from 'seamless-immutable';
import { bindActionCreators } from 'redux';
import { connect } from 'labrador-redux';
import { createAction } from 'redux-actions';
import WxParse from '../../templates/wxParse/wxParse';
import Comment from '../../components/comment/comment';

const { any } = PropTypes;

class Detail extends Component {
    static propTypes = {};

    static defaultProps = {
        info: {},
        comments: [],
    };

    constructor(props) {
        super(props);
        this.state = immutable({ shared: false });
    }

    children() {
        let comments = this.props.comments || [];

        return {
            comments: comments.map((comment) => ({
                component: Comment,
                key: comment.id,
                props: {
                    ...comment
                }
            })),
        }
    }

    onUpdate(props) {
        if (props.info.title && props.info.info) {
            this.page.setData({
                item: props.info.info,
                title: props.info.title,
            });
            WxParse.wxParse('article', 'md', props.info.info, this.page, 5);
        }
    }

    onLoad(options) {
        this.storage = options;
        this.setState({ fromType: options.fromType });
        this.initPostDetail(options.id, options.form_id);
        this.props.checkLoginStatus();
    }

    async initPostDetail(id, form_id) {
        this.props.initPostDetail({ id, form_id });
    }

    handleReachBottom() {
        let { info, commentPageNum, commentEnd } = this.props;
        if (!commentEnd) {
            commentPageNum++;
            this.props.fetchComments({ pageNum: commentPageNum, id: info.id })
        }
    }

    // 设置分享
    onShareAppMessage() {
        return {
            title: this.props.info.title,
            desc: '萌酱酱选辅食一个致力于帮助新手爸妈为宝宝轻松制作辅食的APP。',
            path: '/pages/detail/index?id=' + this.props.info.id + '&fromType=share',
            imageUrl: this.props.info.img
        }
    }

    postComment() {
        wx.navigateTo({ url: '/pages/postcomment/index?id=' + this.props.info.id });
    }

    backtoIndex(e) {
        this.props.uploadFormId({ form_id: e.detail.formId });
        wx.switchTab({
            url: '/pages/index/index'
        });
    }
}

export default connect(
    ({ post }) => ({ info: post.info, comments: post.comments, commentPageNum: post.commentPageNum, commentEnd: post.commentEnd }),
    (dispatch) => bindActionCreators({
        initPostDetail: createAction('post/initPostDetail', (params) => (params)),
        fetchComments: createAction('post/fetchComments', (params) => (params)),
        checkLoginStatus: createAction('user/checkLoginStatus', (params) => (params)),
        uploadFormId: createAction('user/uploadFormId', (params) => (params)),
    }, dispatch)
)(Detail);